import 'package:flutter/material.dart';
import 'package:mall/components/product_list.dart';
import 'package:mall/constants.dart';
import 'package:mall/core/models/store_detail_req.dart';
import 'package:mall/core/services/new_api.dart';
import 'package:provider/provider.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../../../theme.dart';

/// 店铺所有商品
class StoreProduct extends StatefulWidget {
  final int storeId;

  const StoreProduct({
    Key key,
    this.storeId,
  }) : super(key: key);

  @override
  _StoreProductState createState() => _StoreProductState();
}

class _StoreProductState extends State<StoreProduct> {
  String _error;
  List<MapEntry<String, String>> _list;

  @override
  void initState() {
    super.initState();
    _fetchStoreDetail();
  }

  @override
  Widget build(BuildContext context) {
    return _error == null && _list == null
        ? Center(
            child: CircularProgressIndicator(),
          )
        : _list == null
            ? Center(
                child: Text('$_error'),
              )
            : _buildContent(context);
  }

  DefaultTabController _buildContent(BuildContext context) {
    return DefaultTabController(
      length: _list.length,
      child: Column(
        children: [
          SizedBox(
            height: 30.w,
            child: TabBar(
              tabs: List.generate(
                _list.length,
                (index) => Tab(text: _list[index].value),
              ),
              isScrollable: true,
              indicatorSize: TabBarIndicatorSize.label,
              labelColor: Theme.of(context).primaryColor,
              unselectedLabelColor: kTextColor,
            ),
          ),
          Expanded(
            child: TabBarView(
              children: List.generate(
                _list.length,
                (index) => ProductList(
                  storeId: widget.storeId,
                  areaId: int.tryParse(_list[index].key),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 拉取店铺分区信息
  void _fetchStoreDetail() async {
    final api = context.read<NewApi>();
    try {
      final req = StoreDetailReq(
        clientId: clientId,
        storeId: widget.storeId,
      );
      final storeDetail = await api.storeDetail(req);
      if (!mounted) {
        return;
      }
      setState(() {
        _list = storeDetail.storeAreaIdNameMap.entries.toList();
        _list.insert(0, MapEntry('0', '全部商区'));
      });
    } catch (e) {
      debugPrint('$e');
    }
  }
}
